package com.flyco.modules.stm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyco.modules.pms.service.IPmsSkuStockService;
import com.flyco.modules.stm.entity.StmChannelInfo;
import com.flyco.modules.stm.entity.StmChannelProduct;
import com.flyco.modules.stm.entity.StmChannelProductApplyItem;
import com.flyco.modules.stm.entity.StmChannelStoreRelation;
import com.flyco.modules.stm.mapper.StmChannelProductMapper;
import com.flyco.modules.stm.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 渠道产品表
 * @Author: flyco
 * @Date: 2023-06-21
 * @Version: V1.0
 */
@Service
public class StmChannelProductServiceImpl extends ServiceImpl<StmChannelProductMapper, StmChannelProduct> implements IStmChannelProductService {

    @Autowired
    private StmChannelProductMapper channelProductMapper;
    @Autowired
    private IStmChannelProductApplyItemService applyItemService;
    @Autowired
    private IStmChannelProductApplyService applyService;
    @Autowired
    private IStmChannelInfoService channelInfoService;
    @Autowired
    private IPmsSkuStockService skuStockService;
    @Autowired
    private IStmChannelStoreRelationService channelStoreRelationService;


    @Override
    public List<StmChannelProduct> getByChannelIdAndProductSnAndBeginTime(Integer channelId, String productSn, Date beginTime) {

        LambdaQueryWrapper<StmChannelProduct> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StmChannelProduct::getChannelId, channelId)
                .eq(StmChannelProduct::getProductSn, productSn)
                .eq(StmChannelProduct::getBeginTime, beginTime);
        return channelProductMapper.selectList(wrapper);
    }

    /**
     * 把StmChannelProductApplyItem的记录合并到StmChannelProduct表中
     */
    @Override
    public void mergeIntoChannelProduct(String productApplyItemIds) {

        List<String> ids = Arrays.asList(productApplyItemIds.split(","));
        Integer applyId = 0;
        for (String id : ids) {
            StmChannelProductApplyItem itemInfo = applyItemService.getById(id);
            mergeIntoChannelProduct(itemInfo);
            applyId = itemInfo.getApplyId();
        }

        //判断是否都审批通过，如果都审批通过，则把申请记录的状态也改成审批通过
        applyService.updateApplyStatusByApprove(applyId);
    }

    private void mergeIntoChannelProduct(StmChannelProductApplyItem itemInfo) {
        LambdaQueryWrapper<StmChannelProduct> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StmChannelProduct::getChannelId, itemInfo.getChannelId())
                .eq(StmChannelProduct::getProductSn, itemInfo.getProductSn())
                .in(StmChannelProduct::getStatus, 0, 1);
        List<StmChannelProduct> list = list(queryWrapper);

        //1 判断是否生效，如果已经生效，则跟表中记录比较，如果比表中记录更接近当前，则采用当前的记录信息，否则放弃更新
        boolean isBegin = itemInfo.getBeginTime().compareTo(new Date()) <= 0;
        itemInfo.setStatus(isBegin ? 1 : 0);
        //还没有相同产品，直接插入
        if (CollectionUtils.isEmpty(list)) {
            saveChannelProduct(itemInfo);
            return;
        }

        if (isBegin) {
            List<StmChannelProduct> productList = list.stream().filter(o -> o.getStatus().equals(1)).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(productList)) {
                //还没有生效的相同产品，直接插入
                saveChannelProduct(itemInfo);
                return;
            }
            //已有生效，但从时间看比当前时间小，以前的生效记录改成已过期，并新插入一条生效的记录
            List<StmChannelProduct> needUpdate = productList
                    .stream()
                    .filter(o -> itemInfo.getBeginTime().compareTo(o.getBeginTime()) >= 0)
                    .map(o -> o.setStatus(2))
                    .collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(needUpdate)) {
                updateBatchById(needUpdate);
                saveChannelProduct(itemInfo);
            }
            return;
        }
        //2 时间还没未到，且无相同时间的记录，直接插入
        StmChannelProduct product = list.stream().filter(o -> o.getBeginTime().equals(itemInfo.getBeginTime())).findFirst().orElse(null);
        if (product == null) {
            saveChannelProduct(itemInfo);
            return;
        }
        //有相同时间的记录，把价格更新成新的导入的记录
        product.setPrice(itemInfo.getPrice());
        updateById(product);
        return;

    }


    private void saveChannelProduct(StmChannelProductApplyItem itemInfo) {
        StmChannelProduct channelProduct = new StmChannelProduct();
        BeanUtils.copyProperties(itemInfo, channelProduct);
        save(channelProduct);
    }

    /**
     * 批量把绑定了该渠道的经销商进行sku表更新
     */
    private void saveSkuByChannelId(Integer channelId) {

        List<StmChannelStoreRelation> relationList = channelStoreRelationService.getByChannelId(channelId);
        for (StmChannelStoreRelation relation : relationList) {

            channelStoreRelationService.saveByChannelId(relation.getChannelId(), relation.getStoreId());
        }
    }


    /**
     * 财务审批通过后，把申请的价格更新到渠道表中去
     */
    @Override
    public void mergeIntoChannelProductByApplyId(Integer applyId) {

        LambdaQueryWrapper<StmChannelProductApplyItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StmChannelProductApplyItem::getApplyId, applyId);
        List<StmChannelProductApplyItem> productApplyItems = applyItemService.list(queryWrapper);
        productApplyItems.forEach(itemInfo -> {
            mergeIntoChannelProduct(itemInfo);
        });

        //审批通过后，把新增加的产品更新到绑定了该渠道的经销商SKU表中。
        saveSkuByChannelId(productApplyItems.get(0).getChannelId());
    }

    @Override
    public List<StmChannelProduct> getByChannelId(Integer channelId) {
        LambdaQueryWrapper<StmChannelProduct> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StmChannelProduct::getChannelId, channelId);
        return list(queryWrapper);
    }

//    @Override
//    public void setChannelProductStatus() {
//
//        // 1 获取所有有效渠道列表
//        LambdaQueryWrapper<StmChannelInfo> channelInfoWrapper = new LambdaQueryWrapper<>();
//        channelInfoWrapper.eq(StmChannelInfo::getStatus, 1);
//        List<StmChannelInfo> channelInfoList = channelInfoService.list(channelInfoWrapper);
//
//        // 2每个渠道获取下面的产品列表
//        for (StmChannelInfo channelInfo : channelInfoList) {
//            LambdaQueryWrapper<StmChannelProduct> productWrapper = new LambdaQueryWrapper<>();
//            productWrapper.eq(StmChannelProduct::getChannelId, channelInfo.getId())
//                    .in(StmChannelProduct::getStatus, 0, 1);
//            List<StmChannelProduct> productList = list(productWrapper);
//
//            //循环每个产品，查看是否有刚符合条件生效的产品，如果有，把状态从0改成1，并把该产品下的其他有效记录设置成过期，一个产品只能有一个有效的
//            updateStatus(productList, channelInfo.getId());
//        }
//    }

//    private void updateStatus(List<StmChannelProduct> productList, Integer channelId) {
//
//        //循环每个产品，查看是否有刚符合条件生效的产品，如果有，把状态从0改成1，
//        //并把该产品下的其他有效记录设置成过期，一个产品只能有一个有效的
//        List<StmChannelProduct> needUpdate = new ArrayList<>();
//        for (StmChannelProduct product : productList) {
//            if (product.getStatus().equals(0) && product.getBeginTime().compareTo(new Date()) < 0) {
//                List<StmChannelProduct> channelProduct = productList.stream()
//                        .filter(o -> o.getStatus().equals(1) && o.getProductSn()
//                                .equals(product.getProductSn()))
//                        .collect(Collectors.toList());
//                if (!CollectionUtils.isEmpty(channelProduct)) {
//                    channelProduct.forEach(o -> {
//                        o.setStatus(2);
//                        needUpdate.add(o);
//                    });
//                }
//                product.setStatus(1);
//                needUpdate.add(product);
//            }
//        }
//        if (!CollectionUtils.isEmpty(needUpdate)) {
//            updateBatchById(needUpdate);
//        }
//    }

    @Override
    public StmChannelProduct getValidateByChannelIdAndProductSn(Integer channelId, String productSn) {
        LambdaQueryWrapper<StmChannelProduct> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StmChannelProduct::getChannelId, channelId)
                .eq(StmChannelProduct::getProductSn, productSn)
                .eq(StmChannelProduct::getStatus, 1);
        List<StmChannelProduct> list = channelProductMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0);
        } else {
            return null;
        }
    }

}
